import { PaginationQueryDto } from 'src/common/dto/paginationQuery.dto';
import { ArticleThumbsEntity } from './../../entity/article-thumbs.entity';
import { CreateArticleDto } from './dto/createArticle.dto';
import { CommonRepService } from './../../common/services/commonRep.service';
import { ArticletEntity } from './../../entity/article.entity';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class ArticleService extends CommonRepService<ArticletEntity, CreateArticleDto>{

    constructor(
        @InjectRepository(ArticletEntity) private readonly articleRep: Repository<ArticletEntity>,
        @InjectRepository(ArticleThumbsEntity) private readonly thumpRep: Repository<ArticleThumbsEntity>
    ) {
        super(articleRep);
        this.relations = [];
    }

    /**
     * 查询文章详情
     * @param articleId 
     * @param userId 
     */
    async queryDetail(articleId:string,userId:string):Promise<ArticletEntity> {
        return this.articleRep.query(`
            SELECT a.*,(CASE 
                WHEN th.uid THEN
                    1
                ELSE
                    0
            END ) as isThumb
            FROM article a
            LEFT JOIN article_thumbs th ON th.articleId = a.id AND  th.uid = ${userId} AND a.id = ${articleId}
            WHERE a.id = 1
        `)
    }

    /**
     * 获取列表
     */
    async getList(dto: PaginationQueryDto,userId:string) {
        return this.articleRep.query(`
            SELECT a.*,(CASE 
                WHEN th.uid THEN
                    1
                ELSE
                    0
            END ) as isThumb
            FROM article a
            LEFT JOIN article_thumbs th ON th.articleId = a.id AND  th.uid = ${userId}
        `)
    }
    /**
     *  点赞和取消点赞
     *  @param articleId 
     *  @param userId 
     */
    async thumb(articleId: string, userId: string): Promise<any> {
        const one = await this.thumpRep.findOne({ articleId });
        if (one) {
            this.thumpRep.delete({ articleId });
        } else {
            const ety = new ArticleThumbsEntity();
            ety.articleId = articleId;
            ety.uid = userId;
            this.thumpRep.save(ety);
        }
    }
}
